package com.hunantv.mglive.widget.Toast;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.hunantv.mglive.R;
import com.hunantv.mglive.common.BuildConfig;
import com.hunantv.mglive.common.FormEncodingBuilderEx;
import com.hunantv.mglive.common.MaxApplication;
import com.hunantv.mglive.data.ResultModel;
import com.hunantv.mglive.data.StarLiveDataModel;
import com.hunantv.mglive.ui.live.StarDetailActivity;
import com.hunantv.mglive.utils.GlideRoundTransform;
import com.hunantv.mglive.utils.HttpUtils;
import com.hunantv.mglive.utils.L;
import com.hunantv.mglive.utils.MGTVUtil;
import com.hunantv.mglive.utils.RoleUtil;
import com.hunantv.mglive.utils.StringUtil;
import com.hunantv.mglive.utils.Toast;
import com.hunantv.mglive.widget.PersonValueAnim;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

/**
 * Created by admin on 2016/3/1.
 */
public class LiveStarDialog extends AlertDialog implements HttpUtils.callBack, View.OnClickListener {
    private ImageView mPhoto;
    private ImageView mRole;
    private TextView mName;
    private TextView mTips;
    private TextView mDynamic;
    private TextView mFans;
    private TextView mFollow;
    private Button mFollowBtn;
    private ImageButton mClose;
    private ImageButton mReport;
    private HttpUtils mHttp;
    private StarLiveDataModel mStar;
    private PersonValueAnim mPersonValueAnim;
    private ConfirmDialog mReportDialog;
    private boolean isReport = false;

    private boolean mIsFollow = false;
    public LiveStarDialog(Context context) {
        super(context);
        mHttp = new HttpUtils(context, this);
    }

    public LiveStarDialog(Context context, StarLiveDataModel star) {
        super(context);
        this.mStar = star;
        mHttp = new HttpUtils(context, this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.layout_live_star_dialog);
        setCanceledOnTouchOutside(true);
        initUI();

        Window window = getWindow(); //得到对话框
        window.setWindowAnimations(R.style.dialog_window_anim); //设置窗口弹出动画
        window.setBackgroundDrawableResource(R.drawable.live_star_dialog_bg_shape); //设置对话框背景
//        window.setDimAmount(0l);

        window.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams lp = window.getAttributes();
        DisplayMetrics d = getContext().getResources().getDisplayMetrics(); // 获取屏幕宽、高用
        lp.width = (int) (d.widthPixels * 0.72);
        window.setAttributes(lp);
    }

    public void initUI() {
        mReport = (ImageButton) findViewById(R.id.iv_report);
        mReport.setOnClickListener(this);
        mClose = (ImageButton) findViewById(R.id.iv_close);
        mClose.setOnClickListener(this);
        mPhoto = (ImageView) findViewById(R.id.iv_photo);
        mPhoto.setOnClickListener(this);
        mRole = (ImageView) findViewById(R.id.iv_role);
        mName = (TextView) findViewById(R.id.tv_name);
        mTips = (TextView) findViewById(R.id.tv_tips);
        mDynamic = (TextView) findViewById(R.id.tv_dynamic);
        mFans = (TextView) findViewById(R.id.tv_fans);
        mFollow = (TextView) findViewById(R.id.tv_follow);
        mFollowBtn = (Button) findViewById(R.id.b_follow);
        mPersonValueAnim = new PersonValueAnim(getContext(), (ViewGroup) mFollowBtn.getParent());
        if (mStar != null) {
            Glide.with(getContext()).load(mStar.getPhoto())
                    .placeholder(R.drawable.default_icon_preload).error(R.drawable.default_icon)
                    .transform(new GlideRoundTransform(getContext(), R.dimen.height_80dp))
                    .into(mPhoto);
            Glide.with(getContext()).load(RoleUtil.getRoleIcon(mStar.getRole())).into(mRole);
            mName.setText(mStar.getNickName());
            mTips.setText(mStar.getUserDesc());
            mDynamic.setText(mStar.getDynamicCount());
            mFans.setText(mStar.getFansCount());
            mFollow.setText(mStar.getFollowCount());
            mFollowBtn.setOnClickListener(this);
            changeFollowBtn(mStar);
        }
        mReportDialog = new ConfirmDialog(getContext(), R.string.tips_live_report, R.string.ok_1, R.string.cancel);
        mReportDialog.setClicklistener(new ConfirmDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                liveReport();
                mReportDialog.dismiss();
            }

            @Override
            public void doCancel() {
                mReportDialog.cancel();
            }
        });
    }

    private void liveReport(){
        if(mStar != null)
        {
            Map<String, String> body = new FormEncodingBuilderEx()
                    .add("aid", mStar.getUid())
                    .add("uid", MaxApplication.getApp().getUid())
                    .add("token", MaxApplication.getApp().getToken())
                    .add("content", "")//举报内容暂时不传
                    .build();
            post(BuildConfig.URL_LIVE_REPORT, body);
        }
    }

    private void followStar(String starId) {
        Map<String, String> body = new FormEncodingBuilderEx()
                .add("uid", MaxApplication.getApp().getUid())
                .add("token", MaxApplication.getApp().getToken())
                .add("followid", starId)
                .build();
        post(BuildConfig.URL_ADD_FOLLOW, body);
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.iv_report) {
            if (isReport) {
                Toast.makeText(getContext(), R.string.tips_live_report_repeat, Toast.LENGTH_SHORT).show();
            } else {
                if (!mReportDialog.isShowing()) {
                    mReportDialog.show();
                }
            }

        } else if (i == R.id.iv_close) {
            dismiss();

        } else if (i == R.id.iv_photo) {
            toStarRoom();

        } else if (i == R.id.b_follow) {
            if (MaxApplication.getInstance().isLogin()) {
                if (!mIsFollow) {
                    //粉她
                    followStar(mStar.getUid());
                }
            } else {
                MGTVUtil.getInstance().login(MaxApplication.getAppContext());
            }

        }
    }

    @Override
    public void onSucceed(String url, ResultModel resultModel) throws JSONException, RemoteException {
        if (BuildConfig.URL_ADD_FOLLOW.equals(url)) {
            if (mStar != null) {
                changeFollowBtn(mStar);
            }
            if (mPersonValueAnim != null) {
                mPersonValueAnim.startPersonValueAnim(mFollowBtn);
            }
            mFans.setText((Integer.parseInt(mFans.getText().toString()) + 1) + "");
            Toast.makeText(getContext(), "已粉TA", Toast.LENGTH_SHORT).show();
            L.d("LiveStarDialog", "关注成功");
        }else if(BuildConfig.URL_LIVE_REPORT.equals(url))
        {
            isReport = true;
            Toast.makeText(getContext(), R.string.tips_live_report_success, Toast.LENGTH_SHORT).show();
        }
        else if(BuildConfig.URL_GET_IS_FOLLOWED.equals(url))
        {
            try {
                JSONObject jsonData = new JSONObject(resultModel.getData());
                boolean isFollow = jsonData.getBoolean("isFollowed");
                if (isFollow) {
                    mIsFollow = true;
                    mFollowBtn.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.follow_yes_bg_shape));
                    mFollowBtn.setText("已粉");
                    mFollowBtn.setAlpha(0.1f);
                } else {
                    mFollowBtn.setBackgroundDrawable(getContext().getResources().getDrawable(R.drawable.follow_no_bg_shape));
                    mFollowBtn.setText("粉TA");
                    mFollowBtn.setAlpha(1.0f);
                }
            }catch (Exception e){

            }
        }
    }

    private void toStarRoom(){
        if(mStar != null && !StringUtil.isNullorEmpty(mStar.getUid()))
        {
            Intent intent = new Intent(getContext(), StarDetailActivity.class);
            intent.putExtra(StarDetailActivity.KEY_STAR_ID, mStar.getUid());
            getContext().startActivity(intent);
            dismiss();
        }
    }

    private void changeFollowBtn(StarLiveDataModel starModel) {
        mIsFollow = false;
        if(MaxApplication.getInstance().isLogin())
        {
            Map<String, String> param = new FormEncodingBuilderEx()
                    .add("uid", MaxApplication.getInstance().getUid())
                    .add("token", MaxApplication.getInstance().getToken())
                    .add("artistId", starModel != null ? starModel.getUid() : "").build();
            post(BuildConfig.URL_GET_IS_FOLLOWED, param);
        }
    }

    @Override
    public boolean get(String url, Map<String, String> param) {
        return mHttp.get(url, param);
    }

    @Override
    public boolean post(String url, Map<String, String> param) {
        return mHttp.post(url, param);
    }

    @Override
    public void onError(String url, Exception e) {

    }

    @Override
    public Object asyncExecute(String url, ResultModel resultModel) {
        return null;
    }

    @Override
    public void onFailure(String url, ResultModel resultModel) {

    }

    public void setStar(StarLiveDataModel mStar) {
        this.mStar = mStar;
    }
}
